import Head from "next/head";
import { useEffect, useState } from "react";
import Link from "next/link";

export default function Users() {
  const [users, setUsers] = useState([]);
  //   const [userIdToDelete, setUserIdToDelete] = useState(null);

  const deleteUser = async (id) => {
    // setUserIdToDelete(id);
    try {
      const res = await fetch(`/api/users?id=${id}`, { method: "DELETE" });
      if (res.ok) {
        const updatedUsers = users.filter((user) => user.id !== id);
        setUsers(updatedUsers);
      } else {
        alert("删除用户失败");
      }
    } catch (error) {
      console.error("删除用户时出错:", error);
      alert("删除用户失败");
    } finally {
      //   setUserIdToDelete(null);
    }
  };

  useEffect(() => {
    const fetchUsers = async () => {
      const res = await fetch("/api/users");
      const data = await res.json();
      setUsers(data);
    };
    fetchUsers();
  }, []);

  return (
    <div className="container mx-auto">
      <Head>
        <title>用户管理</title>
      </Head>
      <h1 className="text-2xl font-bold my-4">用户列表</h1>
      <Link href="/users/create" className="bg-blue-500 text-white p-2 rounded">
        创建用户
      </Link>
      <table className="min-w-full border-collapse border border-gray-200 mt-4">
        <thead>
          <tr>
            <th className="border border-gray-300 px-4 py-2">ID</th>
            <th className="border border-gray-300 px-4 py-2">姓名</th>
            <th className="border border-gray-300 px-4 py-2">邮箱</th>
            <th className="border border-gray-300 px-4 py-2">操作</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.id}>
              <td className="border border-gray-300 px-4 py-2">{user.id}</td>
              <td className="border border-gray-300 px-4 py-2">{user.name}</td>
              <td className="border border-gray-300 px-4 py-2">{user.email}</td>
              <td className="border border-gray-300 px-4 py-2 flex gap-2 items-center">
                <Link href={`/users/${user.id}`} className="text-blue-600">
                  编辑
                </Link>
                <button
                  onClick={() => deleteUser(user.id)}
                  className="text-red-600 bg-red-200 border border-red-300 rounded px-2 py-1 hover:bg-red-300 focus:outline-none focus:border-red-400 focus:ring focus:ring-red-300 focus:ring-opacity-50 transition duration-300 ease-in-out"
                >
                  删除
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
